const rewire = require('rewire')
const wdio = require('webdriverio')
const { waitTime } = require('../common/appium.cjs')
const utils = require('../common/utils.cjs')
const {picsearch, picsearchExact} = rewire('./picsearch.cjs')
const {tempMediaPath} = rewire('../config.cjs')
const {saveFile} = rewire('../common/file.cjs')
const {extractPicText} = rewire('../common/ocr.cjs')
const {cutPic} = rewire('../common/pic.cjs')
const {createCacheFn} = rewire('../common/combinator.cjs')

async function startApp() {

    const opts = {
        path: '/wd/hub',
        port: 4723,
        capabilities: {
            "platformName": "Android",
            "platformVersion": "6.0.1",
            "deviceName": "xiaomi",
            "appPackage": "com.netease.my",
            "appActivity": "com.netease.my.Client",
            "automationName": "UiAutomator2",
            "newCommandTimeout": 3600,
            "noReset": true
        }
    }

    let client = await wdio.remote(opts)
    return client
}

async function loginGame(client) {
    await casualClick(client)
    await clickIfExists(client, "close.png")
    await clientWaitForExists(client, 'fuwuqi.png', 10)
    await clickElem(client, loginBtn)
    await clientWaitForExists(client, 'zhiyin.png', 10)
}

async function autoPlot(client) {
    await clickFirstTask(client)
    await waitTime(client, 1500)
    await dClickContinueBtn(client)

    await clickResUseBtn(client)

    // 点击福利按钮
    await clickFuliBtn()

    await clickShengjilibaoBtn()
    await clickFirstLibaoBtn()

    await closeFuli()

    await clickFirstTask(client)

    await dClickContinueBtn(client)
    await dClickContinueBtn(client)
}

async function casualClick(client) {
    const x = utils.ramdomRange(50, 900)
    const y = utils.ramdomRange(50, 450)
    await clickClient(client, {x, y})
}

async function clickClient(client, point) {
    await client.touchPerform([
        { action: 'press', options: point},
        { action: 'wait', options: { ms: 50 }},
        { action: 'release' }
    ])
}


async function clientDrag(client, from, to) {
    await client.touchPerform([
        { action: 'press', options: from},
        { action: 'wait', options: { ms: 500 }},
        { action: 'moveTo', options: to},
        { action: 'release' }
    ])
}



async function clickElem(client, elem) {
    const x = utils.ramdomRange(elem.minX, elem.maxX)
    const y = utils.ramdomRange(elem.minY, elem.maxY)
    await clickClient(client, {x, y})
    await waitTime(client, 500)
}

function createElem(p1, p2) {
    return {
        minX: p1.x,
        maxX: p2.x,
        minY: p1.y,
        maxY: p2.y,
    }
}

function createElem2(point, width, heigth) {
    return createElem(point, {x: (point.x + width), y: (point.y + heigth)})
}

// 通过python接口创建元素
function createElemByPyPoints(p1, p2, p3, p4) {
    const ps = [p1, p2, p3, p4]
    ps.sort(function(a, b) {
        return (Math.pow(a.x, 2) + Math.pow(a.y, 2)) - (Math.pow(b.x, 2) + Math.pow(b.y, 2))
    })
    return createElem(ps[0], ps[3])
}


const mediaSourcePath = 'E:/project/private/roam/MakeMoney/gua/media/'

// 通过模糊算法
async function createElemByPic(client, picPath) {
    const rs = await findPicFuzzy(client, picPath)
    if (rs.length > 0) {
        const elem = createElemByPyPoints(...(rs.map(item => {return {x: Math.floor(item[0]), y: Math.floor(item[1])}})))
        return elem
    }
    else {
        return false
    }
}

// 使用精确算法
async function createElemByPic2(client, picPath) {
    const bigPic = await takeScreenshot(client)
    const rs = await findPic(client, picPath)
    console.log(rs)
    if (rs.length > 0) {
        const elem = createElem2({x: rs[0][0], y: rs[0][1]}, rs[1], rs[2])
        return elem
    }
    else {
        return false
    }
}

async function createOffsetElem(client, picPath, offsetX, offsetY, width, heigth) {
    const rs = await findPic(client, picPath)
    if (rs.length > 0) {
        const elem = createElem2({x: (rs[0][0] + offsetX), y: (rs[0][1] + offsetY)}, width, heigth)
        return elem
    }
    else {
        return false
    }
}

async function createFuzzyOffsetElem(client, picPath, offsetX, offsetY, width, heigth) {
    const rs = await findPicFuzzy(client, picPath)
    console.log(rs)
    if (rs.length > 0) {
        const elem = createElemByPyPoints(...(rs.map(item => {return {x: Math.floor(item[0]), y: Math.floor(item[1])}})))
        return elem
    }
    else {
        return false
    }
}


async function takeScreenshot(client) {
    const base64 = await client.takeScreenshot()
    const tmpPath = tempMediaPath + '/tmp.png'
    const rs = utils.base64ToFile2(base64, tmpPath)
    return rs
}



// 刮刮乐
async function guaguale(client) {
    await clickElem(client, fuliBtn)
    await clickElem(client, meirifuliBtn)
    await clickElem(client, dakaiguagualeBtn)
    await clientDrag(client, {x: 735, y: 425}, {x: 1165, y:425})  //TODO
    await clientDrag(client, {x: 735, y: 455}, {x: 1165, y:455})
    await clientDrag(client, {x: 735, y: 485}, {x: 1165, y:485})

    await clickIfExists(client, "guagualeiji1.png", 1)

    await clickClose(client)
    await clickClose(client)
}

async function zhuagui(client) {
    await lingshuang(client)
    await chubeifamo(client)
    await zhaoduiyou(client)
    await kaishizhuagui(client)
    jiantingDuiyou(client)
    jiantingRenwu(client)
}

async function kaishiZhuagui(client) {
    await lingZhuaguiRenwu(client)
    await clickZhuagui
}


async function baotu(client) {
    await clickElem(client, huodongBtn)
    await clickElem(client, await findCanjiaBaotuBtn(client))
    await waitTime(client, 5000)
    await clickIfExists(client, 'tingtingwufang.png', 3)
    await casualClick(client)
    await clickElem(client, await findBaoturenwuTask(client))
    await waitForStandStill(client)

    await openBaoguo(client)
    await findScollAndClick(client, 'baotuIcon.png')
    await clickIfExists(client, 'shiyong.png')
}

async function findScollAndClick(client, picPath) {
    async function loop(times) {
        const btn = await createElemByPic2(client, picPath)
        if (btn) {
            await clickElem(client, btn)
            return true
        }
        else {
            if (times >= 3) {
                throw new Error("找不到对应的图片:" + picPath)
            }
            await clientDrag(client, {x: 900, y: 650}, {x: 1050, y: 200})
            return await loop(times + 1)
        }
    }
    return await loop(0)
}

// 打开物品栏
async function openBaoguo(client) {
    await clickElem(client, baoguoBtn)
}

// 精确寻找
async function findPic(client, pic) {
    const bigPic = await takeScreenshot(client)
    const rs = await picsearchExact({small: mediaSourcePath + pic, big: bigPic})
    return rs
}

// 模糊寻找
async function findPicFuzzy(client, pic) {
    const bigPic = await takeScreenshot(client)
    const rs = await picsearch({small: mediaSourcePath + pic, big: bigPic})
    return rs
}

// 等待人物停止移动
async function waitForStandStill(client) {
    async function loop() {
        const location = await getLocation(client)

        async function doCheck(current) {
            await waitTime(client, 1000)
            const newLoc = await getLocation(client)
            if (location == newLoc) {
                if (current >= 3) {
                    return
                }
                else {
                    await doCheck(current + 1)
                }
            }
            else {
                await loop()
            }

        }
        await doCheck(0)
    }

    await loop()
}

async function getLocation(client) {
    const bigPic = await takeScreenshot(client)
    const path = cutPic(tempMediaPath + '/location.png', bigPic, {x: 150, y: 65}, 100, 25)
    const rs = await extractPicText({path})
    if (rs.length > 0) {
        return rs[0]
    }
    return []
}

async function closePlotView(client) {
    while(true) {
        const btn = await closePlotBtn(client)
        if (btn) {
            await elemClick(btn)
        }
        else {
            break
        }
    }
}

async function clickClose(client) {
    await clickIfExists(client, "close.png", 2)
}



async function clientWaitForExists(client, picPath, limit = 5) {
    async function loop(times) {
        if (times < limit) {
            const rs = await findPic(client, picPath)
            if (rs.length > 0) {
                return true
            }
            else {
                await waitTime(client, 1000)
                return await loop(times + 1)
            }
        }
        else {
            return false
        }
    }
    return await loop(0)
}

// 重试5次，如果还不存在则不处理
async function clickIfExists(client, pic, limit = 5) {
    async function loop(times) {
        if (times < limit) {
            const btn = await createElemByPic2(client, pic)
            if (btn) {
                console.log(btn)
                await clickElem(client, btn)
                return true
            }
            else {
                return await loop(times + 1)
            }
        }
        else {
            return false
        }
    }
    return await loop(0)
}


const loginBtn = createElem2({x: 585, y: 570}, 200, 70)
const touxiangBtn = createElem2({x: 1330, y: 15}, 90, 90)

const fuliBtn = createElem2({x: 15, y: 130}, 60, 60)
const meirifuliBtn = createElem2({x: 225, y: 140}, 200, 70)
const dakaiguagualeBtn = createElem2({x: 970, y: 700}, 200, 45)
const fuliCloseBtn = createElem2({x: 1255, y: 35}, 50, 50)
const guaguaLeiji1 = "guagualeiji1.png"
const guaguaJiang1 = createElem2({x: 905, y: 640}, 80, 80)
const guaguaJiang2 = createElem2({x: 1035, y: 640}, 80, 80)
const guaguaJiang3 = createElem2({x: 1165, y: 640}, 80, 80)

const haoyouBtn = createElem2({x: 15, y: 510}, 60, 60)
const shuohuaBtn = createElem2({x: 15, y: 720}, 30, 30)

const firstTaskBtn = createElem2({x: 1160, y: 500}, 250, 100)

// 主界面相关
const dadituBtn = createElem2({x: 10, y: 10}, 80, 80)    // 大地图
const xiaodituBtn = createElem2({x: 95, y: 20}, 150, 60)  // 小地图
const huodongBtn = createElem2({x: 365, y: 10}, 70, 60)  // 活动
const baoguoBtn = createElem2({x: 1360, y: 630}, 55, 50) // 包裹


// 战斗界面相关
const fashuBtn = createElem2({x: 1360, y: 260}, 50, 50)
const tejiBtn = createElem2({x: 1360, y: 370}, 50, 50)
const gongjiBtn = createElem2({x: 1360, y: 480}, 50, 50)
const daojuBtn = createElem2({x: 1360, y: 590}, 50, 50)
const zidongBtn = createElem2({x: 1360, y: 700}, 50, 50)
const fangyuBtn = createElem2({x: 1255, y: 700}, 50, 50)
const fabaoBtn = createElem2({x: 1140, y: 700}, 50, 50)
const baohuBtn = createElem2({x: 1040, y: 700}, 50, 50)
const zhaohuanBtn = createElem2({x: 935, y: 700}, 50, 50)
const taopaoBtn = createElem2({x: 830, y: 700}, 50, 50)
const buzhuoBtn = createElem2({x: 725, y: 700}, 50, 50)

// 活动界面相关
async function findCanjiaBaotuBtn(client) {
    return await createOffsetElem(client, 'baoturenwu.png', 230, 10, 80, 45)
}
async function findCanjiaZhuaguiBtn(client) {
    return await createOffsetElem(client, 'zhuagui.png', 230, 10, 80, 45)
}
async function findCanjiaShimenBtn(client) {
    return await createOffsetElem(client, 'shimen.png', 230, 10, 80, 45)
}
async function findCanjiaKejuBtn(client) {
    return await createOffsetElem(client, 'kejuxiangshi.png', 230, 10, 80, 45)
}
async function findCanjiaYunbiaoBtn(client) {
    return await createOffsetElem(client, 'yunbiao.png', 230, 10, 80, 45)
}
async function findCanjiaBangpaiBtn(client) {
    return await createOffsetElem(client, 'baopairenwu.png', 230, 10, 80, 45)
}


async function findBaoturenwuTask(client) {
    return await createFuzzyOffsetElem(client, 'baoturenwuTask.png', 0, 0, 200, 80)
}


let client = null

(async function() {
    client = await startApp()
    await loginGame(client)
    //await autoPlot(client)
})()


(async function() {
    const btn = await findBaoturenwuTask(client)
    console.log(btn)
    clickElem(client, btn)
})()

clickElem(client, huodongBtn)


clickElem(client, fuliBtn)
